import { Platform } from 'react-native'
import { createStore, applyMiddleware, compose } from 'redux'
import rootReducer from './reducer'
import thunk from 'redux-thunk'
import remote from '@wac/redux-remote'

// 中间件列表
const middlewareList = [thunk, remote]
var enhancer = null

// 开发环境挂载 debug 调试工具
if (process.env.NODE_ENV === 'development') {
  const createLogger = require('redux-logger')
  const devTools = require('remote-redux-devtools')
  const Immutable = require('immutable')

  const logger = createLogger({
    // diff: true,
    // transform Immutable
    stateTransformer: (state) => {
      if (Immutable.Iterable.isIterable(state)) {
        return state.toJS()
      } else {
        return state
      }
    }
  })
  // logger 需要挂载在 middlewareList 最后
  middlewareList.push(logger)
  const devToolsEnhancer = devTools({
    name: Platform.OS,
    hostname: 'localhost',
    port: 5678
  })
  enhancer = compose(applyMiddleware(...middlewareList), devToolsEnhancer)
} else {
  // 生产环境
  enhancer = compose(applyMiddleware(...middlewareList))
}

export default function configureStore(initialState) {
  const store = createStore(
    rootReducer,
    initialState,
    enhancer
  )
  if(module.hot) {
    module.hot.accept(() => {
      const nextRootReducer = require('./reducer')
      store.replaceReducer(nextRootReducer)
    })
  }
  return store
}
